import appService from './appService';
import mergeObj from '../utils/mergeObj';
import aop from '../utils/aop';
// import config from '../utils/config';

/** loading数量记录 */
const loadingCache = {};
class ModelTemplate {
  constructor(model, config) {
    this.model = model;
    this.config = config;
  }

  /** 生成state */
  generateState() {
    let state = {
      /** 分页数据查询条件 */
      query: {
        limit: {
          currentPage: 1,
          pageSize: 10
        }
      },
      /** 后端返回的分页数据 */
      pageInfo: {},
      /** 后端返回的分页数据 */
      data: {},
      /** 单个实体详细信息 */
      detail: {},
      /** 是否正在加载 */
      loading: false
    };
    state = Object.assign({}, state, this.model.state);
    return state;
  }

  /** 生成getters */
  generateGetters() {
    let getters = {};
    getters = Object.assign({}, getters, this.model.getters);
    return getters;
  }

  /** 生成mutations */
  generateMutations() {
    let mutations = {
      saveState(state, payload) {
        // eslint-disable-next-line no-unused-vars
        for (const key in payload) {
          state[key] = payload[key];
        }
      }
    };
    mutations = Object.assign({}, mutations, this.model.mutations);
    return mutations;
  }

  /** 生成action */
  generateActions() {
    let dataSource = this.model.name;

    /** 如果指定了数据源 */
    if (this.config.dataSource) {
      dataSource = this.config.dataSource;
    }
    // if (this.config.invoiceServer) {
    //   dataSource = config.serverProxy + dataSource;
    // } else if (dataSource.substring(0, 1) !== '/') {
    //   dataSource = config.serverProxy + '/' + dataSource;
    // } else {
    //   dataSource = config.serverProxy + dataSource;
    // }

    let queryMethod = '';
    /** 如果指定了查询列表的方法 */
    if (this.config.queryMethod) {
      queryMethod = this.config.queryMethod;
    }
    let getDetailMethod = 'getDetail';
    /** 如果指定了查询一个实体的方法 */
    if (this.config.getDetailMethod) {
      getDetailMethod = this.config.getDetailMethod;
    }
    let saveMethod = '';
    /** 如果指定了保存一个方法 */
    if (this.config.saveMethod) {
      saveMethod = this.config.saveMethod;
    }
    // eslint-disable-next-line
    let batchSaveMethod = 'batchSave.do';
    /** 如果指定了批量保存方法 */
    if (this.config.batchSaveMethod) {
      batchSaveMethod = this.config.batchSaveMethod;
    }
    let localUpdateMethod = 'localUpdate';
    /** 如果指定了更新方法 */
    if (this.config.localUpdateMethod) {
      localUpdateMethod = this.config.localUpdateMethod;
    }
    let globalUpdateMethod = 'globalUpdate';
    /** 如果指定了更新方法 */
    if (this.config.globalUpdateMethod) {
      globalUpdateMethod = this.config.globalUpdateMethod;
    }
    // eslint-disable-next-line
    let batchUpdateMethod = 'batchUpdate.do';
    /** 如果指定了批量更新方法 */
    if (this.config.batchUpdateMethod) {
      batchUpdateMethod = this.config.batchUpdateMethod;
    }
    let deleteMethod = 'delete';
    /** 如果指定了删除方法 */
    if (this.config.deleteMethod) {
      deleteMethod = this.config.deleteMethod;
    }
    // eslint-disable-next-line
    let batchDeleteMethod = 'delete.do';
    /** 如果指定了批量删除方法 */
    if (this.config.batchDeleteMethod) {
      batchDeleteMethod = this.config.batchDeleteMethod;
    }
    const formatResult = function (result) {
      if (result && result.status === 200 && result.data.errorCode === 0) {
        result = result.data;
      } else {
        // result = result.data;
        if (result) {
          // result = {
          //   errorCode: result.status
          // };
          result = result.data;
        }
      }
      return result;
    };
    let actions = {
      /** 查询列表 */
      async query(store, payload) {
        const query = mergeObj(store.state.query, payload);
        let result = await appService.getRequest(`${dataSource}${queryMethod}`, query);
        if (result && result.status === 200 && result.data.errorCode === 0) {
          const newPayload = {
            query: query,
            pageInfo: {}
          };
          if (Object.prototype.toString.call(result.data.data) === '[object Array]') {
            newPayload.pageInfo.list = result.data.data;
          } else {
            newPayload.pageInfo = result.data.data;
          }
          // const newPayload = {
          //   query: query,
          //   pageInfo: {
          //     ...result.data.data
          //   }
          // };
          /** 更新state */
          store.commit('saveState', {
            ...newPayload
          });
        }
        result = formatResult(result);
        return result;
      },

      /** 查询单个实体具体信息 */
      async getDetail(store, payload) {
        let queryDetailMethod=getDetailMethod
        if( getDetailMethod.slice(-1) !== "/"){
          queryDetailMethod=(queryDetailMethod+"/")
        }
        let result = await appService.getRequest(`${dataSource}${queryDetailMethod}${payload}`);
        if (result && result.status === 200) {
          const newPayload = {
            detail: result.data
          };
          /** 更新state */
          store.commit('saveState', { ...newPayload });
        }
        result = formatResult(result);
        return result;
      },

      /** 删除 */
      async delete(store, payload) {
        let result = await appService.deleteRequest(`${dataSource}${deleteMethod}${payload}`);
        if (result && result.status >= 200 && result.status < 300) {
          //干点什么?
        }
        result = formatResult(result);
        return result;
      },

      /** 保存一个实体 */
      async save(store, payload) {
        let result = await appService.postRequest(`${dataSource}${saveMethod}`, payload);
        if (result && result.status >= 200 && result.status < 300) {
          const newPayload = {
            detail: {
              ...result.data
            }
          };
          /** 更新state */
          store.commit('saveState', { ...newPayload });
        }
        result = formatResult(result);
        return result;
      },

      /** 局部更新一个实体 */
      async localUpdate(store, payload) {
        let result = await appService.putRequest(`${dataSource}${localUpdateMethod}`, payload);
        result = formatResult(result);
        return result;
      },

      /** 全局更新一个实体 */
      async globalUpdate(store, payload) {
        let result = await appService.putRequest(`${dataSource}${globalUpdateMethod}`, payload);
        result = formatResult(result);
        return result;
      }
    };
    actions = Object.assign({}, actions, this.model.actions);
    const name = this.model.name;
    /** 给每一个action添加aop */
    // eslint-disable-next-line no-unused-vars
    for (const key in actions) {
      aop.beforeAndAfter(actions, key, function (store, payload) {
        if (loadingCache[name]) {
          loadingCache[name]++;
        } else {
          loadingCache[name] = 1;
        }
        store.commit('saveState', { loading: true });
      }, function (storeAndPayload, result) {
        const store = storeAndPayload[0];
        // let payload = storeAndPayload[1];
        result.then(data => {
          loadingCache[name]--;
          if (loadingCache[name] === 0) {
            store.commit(`saveState`, { loading: false });
          }
        });
        return result;
      });
    }
    return actions;
  }

  /** 生成子models */
  generateModels() {
    return this.model.models;
  }

  createModel() {
    const newmodel = {};
    newmodel.name = this.model.name;
    newmodel.namespaced = true;
    newmodel.state = this.generateState();
    newmodel.mutations = this.generateMutations();
    newmodel.actions = this.generateActions();
    newmodel.getters = this.generateGetters();
    newmodel.models = this.generateModels();
    return newmodel;
  }
}
export default ModelTemplate;
